package com.citywy.view;

import com.citywy.domain.Course;
import com.citywy.domain.Menu;
import com.citywy.domain.User;
import com.citywy.service.CourseService;
import com.citywy.service.MenuService;
import com.citywy.util.PageUtil;
import com.citywy.util.PublicUtil;
import com.citywy.util.UserUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CourseServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String uri=request.getRequestURI();
        String type=uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf("."));
        //跳转到对应的增删改查
        if(type!=null){
            if("load".equals(type)){
                load(request,response);
            }else if("modify".equals(type)){
                modify(request,response);
            }else if("list".equals(type)){
                list(request,response);
            }else if("drop".equals(type)){
                drop(request,response);
            }
        }
    }

    /**
     * 加载页面，包括新页面和修改页面
     */
    public void load(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        long id = PublicUtil.getParam(request,"id",0l);
        CourseService courseService = new CourseService();
        MenuService menuService = new MenuService();
        Course course= courseService.get(id);
        Map<Integer,String> menus = new HashMap<Integer,String>();
        //栏目赋值
        if(course.getId()>0){
            Menu m = menuService.get(course.getEmenu());
            menus.put(m.getLevel(),String.valueOf(m.getId()));
        }
        request.setAttribute("pages",course);
        request.setAttribute("menus",menus);
        request.getRequestDispatcher("/admin/course/course_load.jsp").forward(request, response);
    }

    /**
     * 增加和修改
     * @param request
     * @param response
     */
    public void modify(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        long id = PublicUtil.getParam(request,"id",0l);
        CourseService courseService = new CourseService();
        User user = UserUtil.getLoginUser(request);
        String title=PublicUtil.getParam(request,"title",null);
        String logo = PublicUtil.getParam(request,"logo",null);
        int eMenu = PublicUtil.getParam(request,"Emenu",0);
        String tag =PublicUtil.getParam(request,"tag",null);
        String summary = PublicUtil.getParam(request,"summary",null);
        String content = PublicUtil.getParam(request,"content",null);
        Course course = new Course();
        course.setTitle(title);
        course.setLogo(logo);
        course.setSummary(summary);
        course.setContent(content);
        course.setTag(tag);
        course.setEmenu(eMenu);
        course.setEaid(user.getId());
        boolean b = false;
        String message="";
        String locationhref = "";
        if(id>0){
            course.setId(id);
            b = courseService.updCourse(course);
            if(b){
                message="修改成功";
            }
            //修改返回时返回之前的筛选条件
            locationhref = request.getParameter("locationhref");
            //正则去掉id=xxx&
            if(locationhref.contains("id=")){
                String regex = "";
                if(locationhref.contains("&")){
                    regex = "id=[0-9]*&";
                }else{
                    regex = "id=[0-9]*";
                }
                Pattern pat = Pattern.compile(regex);
                Matcher matcher = pat.matcher(locationhref);
                while (matcher.find()) {
                    String temp = locationhref.substring(matcher.start(),matcher.end());
                    locationhref = locationhref.replaceAll(temp, "");
                }
            }
        }else{
            b = courseService.addCourse(course);
            if(b){
                message = "添加成功！";
            }
        }
        //为了传递修改成功的参数，我们这里都用转发，其实springmvc中默认也是转发
//		response.sendRedirect("/servlets/news/list.htm");
        request.setAttribute("message",message);
        request.getRequestDispatcher("/servlets/course/list.htm"+locationhref).forward(request, response);
    }

    /**
     * 查询列表
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void list(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        CourseService courseService=new CourseService();
        //获取参数
        int pageNow=PublicUtil.getParam(request,"x_now",1);
        int pageSize=PublicUtil.getParam(request,"x_size",25);
        String x_order=PublicUtil.getParam(request,"x_order","id");//根据什么字段排序
        String x_sort=PublicUtil.getParam(request,"x_sort","desc");
        String x_name=PublicUtil.getParam(request,"x_name",null);

        //查询条件
        String condition = null;
        if(x_name!=null && !"".equals(x_name)){
            condition = "title like '%"+x_name+"%'";
        }

        int rowcount=courseService.getRowCount(condition);
        int pageCount=(rowcount-1)/pageSize+1;

        List<Course> list=courseService.getCourseList(condition,pageNow,pageSize,x_order,x_sort);

        //分页参数
        PageUtil pageUtil = new PageUtil(pageNow,pageSize,pageCount,rowcount,x_order,x_sort,x_name);

        request.setAttribute("list", list);
        request.setAttribute("pageutil",pageUtil);
        request.getRequestDispatcher("/admin/course/course_list.jsp").forward(request, response);
    }

    /**
     * 删除单个ID内容
     * @param request
     * @param response
     */
    public void drop(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        long id = PublicUtil.getParam(request,"id",0l);
        if(id>0){
            CourseService courseService = new CourseService();
            boolean b = courseService.delCourse(id);
            if(b){
                response.sendRedirect("/servlets/course/list.htm");
            }
        }
    }
}
